import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { BaseService } from './base';
import { DailyReport } from '../entity/DailyReport';

@Provide()
export class DailyReportService extends BaseService<DailyReport> {
  @InjectEntityModel(DailyReport)
  entity: Repository<DailyReport>;

  async add(data) {
    return await super.add(data);
  }

  async update(data) {
    return await super.update(data);
  }

  async upsert(data) {
    return await super.upsert(data, { conflictPaths: ['id'] });
  }

  async summary(data_date) {
    let where_sql = '';
    if (data_date) {
      where_sql = `WHERE data_date = "${data_date}"`;
    }
    const sql = `
      SELECT
        store_name,
        data_date,
        SUM( order_num ) AS order_num_sum,
        SUM( order_payable_amount ) AS order_payable_amount_sum,
        SUM( erp_cost ) AS erp_cost_sum,
        SUM( product_cost ) AS product_cost_sum,
        SUM( platform_service_fee ) AS platform_service_fee_sum,
        SUM( order_payable_amount ) AS order_payable_amount_sum,
        SUM( service_fee ) AS service_fee_sum,
        SUM( commission ) AS commission_sum,
        SUM( extra_cost ) AS extra_cost_sum,
        SUM( rebate ) AS rebate_sum,
        SUM( profit ) AS profit_sum,
        SUM( rebate ) AS rebate_sum,
        SUM( actual_platform_discount ) AS actual_platform_discount_sum,
        SUM( actual_discounts_for_influencer ) AS actual_discounts_for_influencer_sum
      FROM
        daily_report
      ${where_sql}
      GROUP BY store_name data_date`;
    return await this.entity.query(sql);
  }
}
